﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace hotel.Common
{
    public class ExcelHelper
    {
        /// <summary>
        /// 另存新档按钮
        /// </summary>
        public static string SaveAs(DataGridView dataGrid) //另存新档按钮   导出成Excel
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = false;
            saveFileDialog.Title = "Export Excel File To";

            if (saveFileDialog.ShowDialog() != DialogResult.OK)
                return "";
            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string str = "";
            try
            {
                //写标题
                for (int i = 0; i < dataGrid.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    str += dataGrid.Columns[i].HeaderText;
                }

                sw.WriteLine(str);

                //写内容
                for (int j = 0; j < dataGrid.Rows.Count; j++)
                {
                    string tempStr = "";
                    for (int k = 0; k < dataGrid.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            tempStr += "\t";
                        }
                        if (dataGrid.Rows[j].Cells[k].Value != null)
                            tempStr += dataGrid.Rows[j].Cells[k].Value.ToString();
                        else
                            tempStr += "";
                    }

                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
                return saveFileDialog.FileName;
            }
            catch (Exception e)
            {              
                MessageBox.Show(e.ToString());
                return saveFileDialog.FileName;
            }
            finally
            {
                sw.Close();
                myStream.Close();               
            }
        }

    }
}